<template>
  <div class="table-box">
    <!-- 搜索表单 -->
    <el-form :model="searchForm" ref="searchFormRef" :inline="true" class="search-form">
      <el-form-item label="设备类型" prop="equipmentType">
        <el-input v-model="searchForm.equipmentType" placeholder="请输入设备类型" clearable />
      </el-form-item>
      <el-form-item label="设备名称" prop="equipmentName">
        <el-input v-model="searchForm.equipmentName" placeholder="请输入设备名称" clearable />
      </el-form-item>
      <el-form-item label="设备状态" prop="status">
        <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 180px;">
          <el-option label="运行中" value="RUNNING" />
          <el-option label="停止" value="STOPPED" />
          <el-option label="维护中" value="MAINTENANCE" />
        </el-select>
      </el-form-item>
      <el-form-item label="序列号" prop="serialNumber">
        <el-input v-model="searchForm.serialNumber" placeholder="请输入序列号" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="table-header">
      <el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')">新增设备</el-button>
      <el-button type="danger" :icon="Delete" plain :disabled="selectedRows.length === 0" @click="handleBatchDelete">
        批量删除
      </el-button>
    </div>
    
    <el-table 
      :data="tableData" 
      style="width: 100%" 
      v-loading="loading"
      @selection-change="handleSelectionChange"
      border 
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="equipmentType" label="设备类型" />
      <el-table-column prop="status" label="设备状态" />
      <el-table-column prop="equipmentName" label="设备名称" />
      <el-table-column prop="manufacturer" label="制造商" />
      <el-table-column prop="modelNumber" label="设备型号" />
      <el-table-column prop="serialNumber" label="序列号" />
      <el-table-column prop="location" label="安装位置" />
      <el-table-column label="操作" width="280" fixed="right">
        <template #default="scope">
          <el-button type="primary" link :icon="View" @click="openDrawer('查看', scope.row)" class="operation-btn">查看</el-button>
          <el-button type="primary" link :icon="EditPen" @click="openDrawer('编辑', scope.row)" class="operation-btn">编辑</el-button>
          <el-button type="primary" link :icon="Delete" @click="deleteEquipment(scope.row)" class="operation-btn">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes, prev, pager, next, jumper"
      />
    </div>
    
    <EquipmentDrawer ref="drawerRef" />
  </div>
</template>

<script setup lang="ts" name="equipmentTable">
import { ref, reactive, onMounted } from "vue";
import type { FormInstance } from 'element-plus';
import { ElMessage, ElMessageBox } from "element-plus";
import EquipmentDrawer from "./EquipmentDrawer.vue";
import { CirclePlus, Delete, EditPen, View } from "@element-plus/icons-vue";
import {
  getEquipmentList,
  registerEquipment,
  updateEquipment,
  deleteEquipment as deleteEquipmentApi,
  batchDeleteEquipment,
  type Equipment
} from "@/api/modules/equipment";

const loading = ref(false);
const tableData = ref<Equipment.EquipmentListItem[]>([]);
const searchFormRef = ref<FormInstance>();
const selectedRows = ref<Equipment.EquipmentListItem[]>([]);

// 查询表单
const searchForm = reactive({
  equipmentType: '',
  equipmentName: '',
  status: '',
  serialNumber: ''
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 获取表格数据
const getTableData = async () => {
  loading.value = true;
  try {
    const params = {
      ...searchForm,
      current: pagination.currentPage,
      size: pagination.pageSize
    };
    const res = await getEquipmentList(params);
    tableData.value = res.data.records;
    pagination.total = res.data.total;
  } catch (error) {
    console.error('获取设备列表失败:', error);
    ElMessage.error('获取设备列表失败');
  } finally {
    loading.value = false;
  }
};

// 表格选择项变化
const handleSelectionChange = (rows: Equipment.EquipmentListItem[]) => {
  selectedRows.value = rows;
};

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) return;
  
  ElMessageBox.confirm(
    `确认删除选中的 ${selectedRows.value.length} 条数据吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const ids = selectedRows.value.map(row => row.id);
      await batchDeleteEquipment(ids);
      ElMessage.success('批量删除成功');
      getTableData();
    } catch (error) {
      console.error('批量删除失败:', error);
      ElMessage.error('批量删除失败');
    }
  }).catch(() => {
    // 取消删除
  });
};

// 查询
const handleSearch = () => {
  pagination.currentPage = 1;
  getTableData();
};

// 重置
const handleReset = () => {
  if (!searchFormRef.value) return;
  searchFormRef.value.resetFields();
  pagination.currentPage = 1;
  getTableData();
};

// 分页大小改变
const handleSizeChange = (val: number) => {
  pagination.pageSize = val;
  getTableData();
};

// 当前页改变
const handleCurrentChange = (val: number) => {
  pagination.currentPage = val;
  getTableData();
};

// 删除设备
const deleteEquipment = async (row: Equipment.EquipmentListItem) => {
  try {
    await deleteEquipmentApi(row.id);
    ElMessage.success(`删除【${row.equipmentName}】设备成功`);
    getTableData();
  } catch (error) {
    console.error('删除设备失败:', error)
    ElMessage.error('删除设备失败');
  }
};

// 打开抽屉
const drawerRef = ref<InstanceType<typeof EquipmentDrawer>>();
const openDrawer = (title: string, row: Partial<Equipment.EquipmentListItem> = {}) => {
  const params = {
    title,
    isView: title === "查看",
    row: { ...row },
    api: title === "新增" ? addEquipment : title === "编辑" ? editEquipment : undefined,
    getTableList: getTableData
  };
  drawerRef.value?.acceptParams(params);
};

// 新增设备
const addEquipment = async (params: Equipment.RegisterEquipmentRequestDto) => {
  return await registerEquipment(params);
};

// 编辑设备
const editEquipment = async (params: Partial<Equipment.EquipmentListItem>) => {
  if (!params.id) {
    ElMessage.error("设备ID不能为空");
    return;
  }
  return await updateEquipment(params as Required<Pick<Equipment.EquipmentListItem, 'id'>> & Partial<Equipment.RegisterEquipmentRequestDto>);
};

// 页面加载时获取数据
onMounted(() => {
  getTableData();
});
</script>

<style scoped>

.search-form {
  background-color: #fff;
  padding: 10px;
  border-radius: 4px;
  margin-bottom: 16px;
}

.table-header {
  margin-bottom: 16px;
  display: flex;
  gap: 10px;
}

.el-table {
  flex: 1;
}

:deep(.el-table__row) {
  height: 30px !important;
  line-height: 35px;
}

:deep(.el-table__cell) {
  padding: 12px 0;
}

:deep(.el-table__header-row) {
  height: 65px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  flex-shrink: 0;
}

:deep(.operation-btn) {
  font-size: 16px;
  margin: 0 5px;
}

:deep(.operation-btn .el-icon) {
  font-size: 18px;
  margin-right: 4px;
}
</style>
